package com.zjgeport.zjgdanger;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.joanzapata.android.BaseAdapterHelper;
import com.joanzapata.android.QuickAdapter;
import com.nineoldandroids.view.ViewHelper;
import com.soar.PageInfo;
import com.soar.util.net.rmi.httpxml.HttpCallBack;
import com.soar.util.net.rmi.httpxml.HttpClient;
import com.soar.util.net.rmi.httpxml.HttpMethod;
import com.soar.util.net.rmi.httpxml.HttpResult;
import com.squareup.picasso.Picasso;
import com.zjgeport.zjgdanger.Analysis.AnalysisMainActivity;
import com.zjgeport.zjgdanger.CompanyInfo.CompInfoListActivity;
import com.zjgeport.zjgdanger.Exception.ExceptionMainActivity;
import com.zjgeport.zjgdanger.OnPortDynamics.DangerCountActivity;
import com.zjgeport.zjgdanger.OnPortDynamics.OnPortMainActivity;
import com.zjgeport.zjgdanger.common.ItemDataUtils;
import com.zjgeport.zjgdanger.common.ParamCommon;
import com.zjgeport.zjgdanger.model.Info;
import com.zjgeport.zjgdanger.model.ItemBean;
import com.zjgeport.zjgdanger.model.myApplication;
import com.zjgeport.zjgdanger.widget.CycleViewPager;
import com.zjgeport.zjgdanger.widget.DragLayout;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import q.rorbin.badgeview.QBadgeView;

public class
MainActivity extends AppCompatActivity {

    private LinearLayout dangerCountLL;

    private DragLayout dl;

    private CycleViewPager mCycleViewPager;

    private QuickAdapter<ItemBean> quickAdapter;

    private ImageView ivIcon, ivBottom;

    private ImageView personBtn;

    private ListView lv;

    private TextView tv1,tv2,tv3;

    private Button btn1,btn2,btn3,btn4,btn5,btn6,exitBtn;

    private SharedPreferences.Editor editor;

    private SharedPreferences pref;

    /** Handler What加载数据完毕 **/
    private static final int WHAT_DID_LOAD_DATA = 0;

    /** Handler What更新数据完毕 **/
    private static final int WHAT_DID_REFRESH = 1;

    /** Handler What更多数据完毕 **/
    private static final int WHAT_DID_MORE = 2;

    /** 分页信息 **/
    protected PageInfo pageInfo = new PageInfo();

    private static final double	PROPORTION		= 0.32152;				// 滑动广告位的高宽比

    private HashMap<String,String> sumMap = new  HashMap<String,String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initDragLayout();
        initView();
        initData();
        initData1();
    }

    private void initDragLayout() {
        dl = (DragLayout) findViewById(R.id.dl);
        dl.setDragListener(new DragLayout.DragListener() {
            //界面打开的时候
            @Override
            public void onOpen() {
            }
            //界面关闭的时候
            @Override
            public void onClose() {
            }

            //界面滑动的时候
            @Override
            public void onDrag(float percent) {
                ViewHelper.setAlpha(personBtn, 1 - percent);
            }
        });
    }

    private void initView()
    {
        dangerCountLL = (LinearLayout)findViewById(R.id.DangerLL);
        dangerCountLL.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent1 = new Intent(MainActivity.this, DangerCountActivity.class);
                intent1.putExtra("SUM1", sumMap.get("sum1").toString());
                intent1.putExtra("SUM2", sumMap.get("sum2").toString());
                intent1.putExtra("SUM3", sumMap.get("sum3").toString());
                intent1.putExtra("SUM4", sumMap.get("sum4").toString());
                intent1.putExtra("SUM5", sumMap.get("sum5").toString());
                intent1.putExtra("SUM6", sumMap.get("sum6").toString());
                intent1.putExtra("SUM7", sumMap.get("sum7").toString());
                startActivity(intent1);
            }
        });
        pref = getSharedPreferences(ParamCommon.APP_CACHE_FILE_NAME, Activity.MODE_PRIVATE);
        editor = pref.edit();

        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        ivBottom = (ImageView) findViewById(R.id.iv_bottom);
        personBtn = (ImageView) findViewById(R.id.bubble1);

        TextView userTv = (TextView)findViewById(R.id.username);
        userTv.setText(myApplication.getUser().getUsername());

        tv1 = (TextView)findViewById(R.id.danger_count);
        tv2 = (TextView)findViewById(R.id.work_chuguan);
        tv3 = (TextView)findViewById(R.id.unnormal_chuguan);

        exitBtn = (Button)findViewById(R.id.exitBtn);
        exitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editor.putString(ParamCommon.APP_IS_AUTO_LOGIN,"1");
                editor.putString(ParamCommon.APP_LOGIN_NAME,"");
                editor.putString(ParamCommon.APP_LOGIN_PASSWORD,"");
                editor.commit();
                myApplication.setUser(null);
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });

        btn1 = (Button)findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent(MainActivity.this, AnalysisMainActivity.class);
                startActivity(intent);

            }
        });

        btn2 = (Button)findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent(MainActivity.this, OnPortMainActivity.class);
                startActivity(intent);
               
            }
        });

        btn3 = (Button)findViewById(R.id.btn3);
        btn3.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent(MainActivity.this, ExceptionMainActivity.class);
                startActivity(intent);
            }
        });

        btn4 = (Button)findViewById(R.id.btn4);
        btn4.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent intent = new Intent(MainActivity.this, CompInfoListActivity.class);
                startActivity(intent);
            }
        });


        lv = (ListView)findViewById(R.id.lv);
        lv.setAdapter(quickAdapter=new QuickAdapter<ItemBean>(this,R.layout.item_left_layout, ItemDataUtils.getItemBeans()) {
            @Override
            protected void convert(BaseAdapterHelper helper, ItemBean item) {
                helper.setText(R.id.item_tv,item.getTitle());
            }
        });
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
//                Toast.makeText(MainActivity.this,"Click Item "+position,Toast.LENGTH_SHORT).show();
            }
        });
        personBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dl.open();
            }
        });


        List<Info> mList = new ArrayList<>();
        for (int i=0;i< 1;i++)
        {

            Info  info  = new Info("","");
            mList.add(info);
        }
        mCycleViewPager = (CycleViewPager)findViewById(R.id.cycle_view);
        //设置选中和未选中时的图片
        assert mCycleViewPager != null;
//        mCycleViewPager.setIndicators(R.drawable.dot_s, R.drawable.idot_l);
        mCycleViewPager.setCycle(false);
        //设置轮播间隔时间，默认为4000
        mCycleViewPager.setDelay(2000);
        mCycleViewPager.setData(mList, null);

        WindowManager wm = getWindowManager();
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int screenHeight = getResources().getDisplayMetrics().heightPixels;
        System.out.println("当前屏幕宽度：" + screenWidth + " 高度：" + screenHeight);

        int addHeight = (int) (screenWidth * PROPORTION)+30;
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(screenWidth, addHeight);
        // lp.addRule(RelativeLayout.BELOW, R.id.RelativeLayout00);
        mCycleViewPager.setLayoutParams(lp);

        int widthScreen  = getWindow().getWindowManager().getDefaultDisplay().getWidth();
    }

    public void initData(){

        HttpMethod method = new HttpMethod();
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("selectBaseInfo");
        method.setKvdata(map);
        HttpClient.postdata(new Button(MainActivity.this), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)){
                    HashMap<String,String> map = result.getKvData();
                    if (map != null && map.size() > 0){

                        getExceptCount();
                        // 刷新UI
                        Looper mainLooper = Looper.getMainLooper();
                        MyHandler handler = new MyHandler(mainLooper);
                        Message msg = new Message();
                        msg.what = WHAT_DID_LOAD_DATA;
                        msg.obj = map;
                        handler.sendMessage(msg);
                    }

                }else {
                    Toast.makeText(getApplication(), result.getResultMessage(), 1).show();
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }
                }

            }
        });

    }

    public void initData1(){

        HttpMethod method = new HttpMethod();
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("getDangerTJCout");
        method.setKvdata(map);
        HttpClient.postdata(new Button(MainActivity.this), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)){
                    List<HashMap<String,String>> sumList = result.getDataSet();
                    if (sumList != null && sumList.size() > 0){

                        HashMap<String,String> sumMap1 = (HashMap<String,String>)sumList.get(6);
                        HashMap<String,String> sumMap2 = (HashMap<String,String>)sumList.get(5);
                        HashMap<String,String> sumMap3 = (HashMap<String,String>)sumList.get(4);
                        HashMap<String,String> sumMap4 = (HashMap<String,String>)sumList.get(3);
                        HashMap<String,String> sumMap5 = (HashMap<String,String>)sumList.get(2);
                        HashMap<String,String> sumMap6 = (HashMap<String,String>)sumList.get(1);
                        HashMap<String,String> sumMap7 = (HashMap<String,String>)sumList.get(0);

                        sumMap.put("sum1",sumMap1.get("TOTAL").toString());
                        sumMap.put("sum2",sumMap2.get("TOTAL").toString());
                        sumMap.put("sum3",sumMap3.get("TOTAL").toString());
                        sumMap.put("sum4",sumMap4.get("TOTAL").toString());
                        sumMap.put("sum5",sumMap5.get("TOTAL").toString());
                        sumMap.put("sum6",sumMap6.get("TOTAL").toString());
                        sumMap.put("sum7",sumMap7.get("TOTAL").toString());

                    }

                }else {
                    Toast.makeText(getApplication(), result.getResultMessage(), 1).show();
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }
                }

            }
        });

    }

    private void getExceptCount()
    {
        HttpMethod method = new HttpMethod();
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("getExceptCount");
        method.setKvdata(map);
        HttpClient.postdata(new Button(MainActivity.this), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)){
                    HashMap<String,String> map = result.getKvData();
                    if (map != null && map.size() > 0){

                        // 刷新UI
                        Looper mainLooper = Looper.getMainLooper();
                        MyHandler handler = new MyHandler(mainLooper);
                        Message msg = new Message();
                        msg.what = 999;
                        msg.obj = map;
                        handler.sendMessage(msg);

                    }

                }else {
                    Toast.makeText(getApplication(), result.getResultMessage(), 1).show();
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }
                }
            }
        });
    }

    private class MyHandler extends Handler
    {
        public MyHandler(Looper looper)
        {
            super(looper);
        }

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case WHAT_DID_LOAD_DATA:

                    HashMap<String,String> map = (HashMap<String,String>)msg.obj;
                    String total = map.get("TOTAL").toString();
                    String ZYCOUNT = map.get("ZYCOUNT").toString();
                    String YCCOUNT = map.get("YCCOUNT").toString();

                    Double t = Double.parseDouble(total)/10000;
                    NumberFormat formatter = new DecimalFormat("0.##");
                    String totalStr = formatter.format(t);

                    tv1.setText(totalStr);
                    tv2.setText(ZYCOUNT);
                    tv3.setText(YCCOUNT);

                    break;
                case 999:

                    HashMap<String,String> dataMap = (HashMap<String,String>)msg.obj;
                    String count = dataMap.get("YCCOUNT").toString();
                    new QBadgeView(getApplicationContext()).bindTarget(btn3).setBadgeNumber(Integer.parseInt(count));

                    break;

                default:
                    break;
            }
        }
    }


    /**
     * 轮播图点击监听
     */
    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(Info info, int position, View imageView) {

            if (mCycleViewPager.isCycle()) {
                position = position - 1;
            }
//            HashMap<String, String> map = AdList.get(position);
//            Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
//            intent.putExtra("ID", map.get("ID"));
//            intent.putExtra("TITLE", map.get("TITLE"));
//            intent.putExtra("CREATE_USER", map.get("CREATE_USER"));
//            intent.putExtra("DATE", map.get("UPDATE_DATE"));
//            intent.putExtra("COLUMN_CODE", map.get("COLUMN_CODE"));
//            intent.putExtra("FLAG", "0");
//            startActivity(intent);
//            Toast.makeText(getActivity(), info.getTitle() + "选择了--" + position, Toast.LENGTH_LONG).show();
        }


    };

    /**
     * 得到轮播图的View
     * @param context
     * @param url
     * @return
     */
    public static View getImageView(Context context, String url) {
        RelativeLayout rl = new RelativeLayout(context);
        //添加一个ImageView，并加载图片
        ImageView imageView = new ImageView(context);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(layoutParams);
        //使用Picasso来加载图片
        Picasso.with(context).load(R.drawable.ad).into(imageView);
        //在Imageview前添加一个半透明的黑色背景，防止文字和图片混在一起
        ImageView backGround = new ImageView(context);
        backGround.setLayoutParams(layoutParams);
//        backGround.setBackgroundResource(R.color.cycle_image_bg);
        rl.addView(imageView);
        rl.addView(backGround);
        return rl;
    }

    public Bitmap getBitMap(com.zjgeport.zjgdanger.widget.AsyncLoaderImage ali, String imageUrl, final ImageView imageView)
    {
        Bitmap bmp = ali.loadBitmap(imageUrl, new com.zjgeport.zjgdanger.widget.AsyncLoaderImage.ImageCallback()
        {
            public void imageLoaded(Bitmap imageBitmap, String imageUrl)
            {
                if (imageBitmap != null)
                {
                    imageView.setBackgroundDrawable(null);
                    imageView.setImageBitmap(imageBitmap);
                }
                else
                {
                        imageView.setImageResource(R.drawable.news_pic00);
                }
            }
        });
        return bmp;
    }
}
